<template>
  <div class="container">
    <!-- 饼状图容器 -->
    <div ref="chartRef" class="chart"></div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import SimpleSidebar from "@/views/chart/SimpleSidebar.vue";

export default {
  name: 'StatsPieChart',
  components: {SimpleSidebar},
  setup() {
    // 图表DOM引用
    const chartRef = ref(null)
    // 图表实例
    let chartInstance = null

    // 初始化图表
    const initChart = () => {
      if (chartRef.value) {
        // 初始化ECharts实例
        chartInstance = echarts.init(chartRef.value)

        // 图表配置
        const option = {
          // 提示框组件
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          // 图例配置
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: ['成功推流', '失败推流', '待推流', '已取消推流']
          },
          // 系列列表
          series: [
            {
              name: '推流情况',
              type: 'pie',
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '18',
                  fontWeight: 'bold'
                }
              },
              labelLine: {
                show: false
              },
              // 饼图数据
              data: [
                { value: 385, name: '成功推流' },
                { value: 340, name: '待推流' },
                { value: 234, name: '已取消推流' },
                { value: 55, name: '失败推流' },
              ],
              // 颜色配置
              color: ['#63f1e5', '#8B5CF6', '#EC4899', '#F59E0B']
            }
          ]
        }

        // 应用配置
        chartInstance.setOption(option)
      }
    }

    // 处理窗口大小变化
    const handleResize = () => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }

    // 组件挂载时初始化图表
    onMounted(() => {
      initChart()
      window.addEventListener('resize', handleResize)
    })

    // 组件卸载前清理
    onBeforeUnmount(() => {
      if (chartInstance) {
        chartInstance.dispose()
        chartInstance = null
      }
      window.removeEventListener('resize', handleResize)
    })

    return {
      chartRef
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  height: 400px;
}

.chart {
  width: 100%;
  height: 100%;
}
</style>